package com.nisure.controller;



import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nisure.AutoKeywordApplication;
import com.nisure.common.CommonData;
import com.nisure.common.CreateJsonObject;
import com.nisure.common.GetHttpJsonobject;
import com.nisure.common.R;
import com.nisure.entity.AccountEntity;
import com.nisure.service.AccountService;

@RestController
public class AccountController {

	@Autowired
	private GetHttpJsonobject getHttpJsonobject;
	@Autowired
	private AccountService accountService;
	@Autowired
	private CreateJsonObject createJsonObject;
		
	private static final Logger logger = LoggerFactory.getLogger(AutoKeywordApplication.class);

	public String getAccesstoken(String code){
		String url = CommonData.uri + "?client_id=" + CommonData.clientId + "&client_secret="
				+ CommonData.clientSecret + "&grant_type=" + CommonData.grantType + "&code="
				+ code + "&redirect_uri=" + CommonData.redirect_uri;
		JSONObject jsonObject = new JSONObject();
		GetHttpJsonobject gethttpjson = new GetHttpJsonobject();
		jsonObject = gethttpjson.httpsRequest(url, "POST", null);
		if (jsonObject == null) {
			return null;
		}
		logger.info(jsonObject.toJSONString());
		String refreshToken = jsonObject.getString("refresh");
		String accessToken = jsonObject.getString("access_token");
		return accessToken;
		
	}
	public JSONObject getAccessTokenByRF(String refreshToken){		
		String refreshurl = "https://open2.baidu.com/oauth2/token";
		String url = refreshurl + "?client_id=" + CommonData.clientId + "&client_secret="
				+ CommonData.clientSecret + "&grant_type=refresh_token&token="
				+ refreshToken;
		JSONObject jsonObject = getHttpJsonobject.httpsRequest(url, "POST", null);
		
		return jsonObject;
		
	}
	public String getRefreshToken(long userId){			
		String refreshToken = accountService.getRefreshToken(userId);
		return refreshToken;
	}
	public int addAccount(long userId,String userName,String refreshToken){
		Map<String,Object> map = new HashMap<String, Object>();
		Date createTime = new Date();
		map.put("userId", userId);
		map.put("userName", userName);
		map.put("refreshToken", refreshToken);
		map.put("createTime", createTime);
		map.put("recentTime", createTime);
		int count = accountService.addAccount(map);
		return count;
	}
	public int updateRefreshToken(long userId,String refreshToken){
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("userId", userId);
		map.put("refreshToken", refreshToken);
		return accountService.updateRefreshToken(map);	
	}
	public JSONObject getAccountInfo(String accessToken){
		JSONObject jsonParams = new JSONObject();
		JSONObject jsonData = new JSONObject();
		List<String> str = new ArrayList<String>();
		str.add("userId");
		jsonParams.put("accountFields", str);		
		jsonData = createJsonObject.getJsonData(accessToken, jsonParams);
		String url = "https://api.baidu.com/json/sms/v4/AccountService/getAccountInfo";							  		 
		JSONObject jsonObject = getHttpJsonobject.httpsRequest(url, "POST", jsonData.toJSONString());
		return jsonObject;
	}
	public List<AccountEntity> queryAccount(String userName){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userName", userName);
		return accountService.queryAccount(map);
	}
	public int updateAccount(long userId,Date recentTime,String refreshToken){
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("userId", userId);
		map.put("recentTime", recentTime);
		map.put("refreshToken", refreshToken);
		return accountService.updateAccount(map);	
	}
	public List<AccountEntity> queryAccountByUserId(long userId){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", userId);
		return accountService.queryAccountByUserId(map);
	}
	public long handleAccount(JSONObject jsonObject){
		String userName = jsonObject.getString("username");
		String refreshToken = jsonObject.getString("refresh_token");		
		List<AccountEntity> account = this.queryAccount(userName);
		long userId=0;
		if(account.isEmpty()){//不存在，添加
			String accessToken = jsonObject.getString("access_token");
			JSONObject jsonObject2 = this.getAccountInfo(accessToken);
			if(jsonObject2.getString("body")==null){
				logger.info(jsonObject2.toJSONString());
				return userId;
			}
			jsonObject2 = JSONObject.parseObject(jsonObject2.getString("body"));
			if(jsonObject2==null||jsonObject2.getString("data")==null){
					return userId;
			}
			JSONArray responseArr = JSONArray.parseArray(jsonObject2.getString("data"));
			JSONObject accountjson = responseArr.getJSONObject(0);
			userId = Long.valueOf(accountjson.getString("userId"));
			this.addAccount(userId, userName, refreshToken);
			
		}else{//存在，更新
			userId = account.get(0).getUserId();
			Date recentTime = new Date();
			this.updateAccount(userId,recentTime, refreshToken);
		}
		return userId;
	}
}
